package slxy.jiangtao.dts.service.sys;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import slxy.jiangtao.dts.core.common.bean.Constants;
import slxy.jiangtao.dts.core.common.service.CommonService;
import slxy.jiangtao.dts.core.util.DateUtils;
import slxy.jiangtao.dts.core.util.StringUtil;
import slxy.jiangtao.dts.entity.business.Task;
import slxy.jiangtao.dts.entity.sys.SystemFiles;
import slxy.jiangtao.dts.entity.sys.User;

import java.io.File;
import java.util.*;

/**
 * Code must be sexy
 * Created by Jiang Tao on 2017/4/18.
 * 说明：
 */
@Service("taskService")
public class TaskService {
    private static final Logger logger = LoggerFactory.getLogger(TaskService.class);
    @Autowired
    private CommonService commonService;
    @Autowired
    private SystemFileService systemFileService;

    /**
     * 删除一个任务，同时删除相关联表
     */
    public void delete(Integer taskid) throws Exception {
        String sql1 = "DELETE FROM user_task_done WHERE task_id = ?";
        commonService.executeSql(sql1, taskid);
        String sql2 = "DELETE FROM user_task WHERE task_id = ?";
        commonService.executeSql(sql2, taskid);
        //删除相应文件
        Task task = commonService.get(Task.class, taskid);
        systemFileService.deleteFileByNoS(task.getFiles());
        commonService.delete(task);
    }

    /**
     * 获取完成此任务的用户姓名(用于详情)
     */
    public List<String> getDoneUser(Integer taskId) {
        String sql = "SELECT b.name name FROM user_task_done a JOIN USER b ON a.user_id=b.id WHERE a.task_id=" + taskId + " and b.statu=" + Constants.STATU_FLAG_NORMAL;
        return commonService.findListbySql(sql);
    }

    /**
     * 添加任务
     */
    public void add(Task task, User user) throws RuntimeException {
        task.setCreator(user.getName());
        task.setCreatTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
        task.setState(Constants.TASK_ING);
        commonService.save(task);
        logger.info(user.getName() + "：创建任务——" + task.getName());
    }

    /**
     * 获取一个任务的负责人字符串集合
     */
    public List<String> getManagersById(String userids) {
        List<String> userNames = new ArrayList();
        Arrays.stream(userids.split(","))
                .forEach(
                        userid ->
                                userNames.add(
                                        commonService.get(User.class, Integer.parseInt(userid)).getName()
                                )
                );
        return userNames;
    }

    /**
     * 任务分析数据获取
     */
    public Map<String, List> getInfo(Integer departId, String time) {
        Map<String, List> resultMap = new HashMap();
        //获取一个部门的所有社员
        DetachedCriteria dc = DetachedCriteria.forClass(User.class);
        dc.add(Restrictions.eq("departId", departId))
                .add(Restrictions.eq("statu", Constants.STATU_FLAG_NORMAL));
        List<User> allUser = commonService.findByDetached(dc);
        List<String> names = new ArrayList<>();
        List<Long> ciShus = new ArrayList<>();
        List<List> bie = new ArrayList<>();//饼图使用,组装形式[ ['username',45.0],['username',26.8]....]
        //获取总次数
        String sql2 = "SELECT count(*) FROM (SELECT * FROM user_task_done WHERE execute_time LIKE '" + time + "%' ) " +
                "a LEFT JOIN USER b ON a.user_id = b.id WHERE b.depart_id = " + departId + " AND b.statu=" + Constants.STATU_FLAG_NORMAL;
        Long counts = commonService.getCountForJdbc(sql2);
        //获取用户集合集合
        List querylist;
        String sql = "SELECT b.NAME username,count(b.id) cishu FROM (SELECT * FROM user_task_done WHERE execute_time LIKE '" + time + "%' ) " +
                "a LEFT JOIN USER b ON a.user_id = b.id WHERE b.depart_id = " + departId + " AND b.statu=" + Constants.STATU_FLAG_NORMAL + " GROUP BY b.id ORDER BY b.id";
        querylist = commonService.findListbySql(sql);
        Optional.ofNullable(allUser).ifPresent(
                userlist ->
                        userlist.forEach(
                                user -> {
                                    List single = new ArrayList();
                                    if (querylist.size() == 0) {
                                        names.add(user.getName());
                                        ciShus.add(0L);
                                    } else {
                                        for (int i = 0; i < querylist.size(); i++) {
                                            Object[] arr = (Object[]) querylist.get(i);
                                            if (arr[0].toString().equals(user.getName())) {
                                                names.add(user.getName());
                                                ciShus.add(Long.parseLong(arr[1].toString()));

                                                {//饼图添加数据，其他为0的情况不考虑添加
                                                    single.add(user.getName());
                                                    single.add(Float.parseFloat(arr[1].toString()) / counts);
                                                    bie.add(single);
                                                }
                                                break;
                                            } else if (i == querylist.size() - 1 && !arr[0].equals(user.getName())) {
                                                names.add(user.getName());
                                                ciShus.add(0L);
                                            }
                                        }
                                    }
                                }
                        )
        );
        resultMap.put("names", names);
        resultMap.put("ciShus", ciShus);
        resultMap.put("bie", bie);
        return resultMap;
    }

    /**
     * 根据用户名,时间，部门id,获取一个用户完成的任务
     */
    public List<List<String>> getPersonalTasks(String username, String time) {
        List<List<String>> resultList = new ArrayList<>();
        String sql = "SELECT d. NAME, d.execute_time FROM ( SELECT b.task_id task_id FROM (SELECT id FROM USER WHERE NAME = '" +
                username + "') a JOIN user_task_done b ON a.id = b.user_id WHERE b.execute_time LIKE '" +
                time + "%' )c JOIN task d on c.task_id = d.id";
        List<Object[]> lists = commonService.findListbySql(sql);
        Optional.ofNullable(lists).ifPresent(
                list ->
                        list.forEach(
                                task -> {
                                        List<String> list1 = new ArrayList<String>();
                                        list1.add(task[0].toString());
                                        list1.add(task[1].toString());
                                        resultList.add(list1);
                                    }
                        )
        );
        return resultList;
    }
}
